﻿namespace TNet
{
    using System;
    using System.Net;
    using System.Threading;

    public class LobbyServerLink
    {
        protected IPEndPoint mExternal;
        protected GameServer mGameServer;
        protected IPEndPoint mInternal;
        private LobbyServer mLobby;
        private long mNextSend;
        protected bool mShutdown;
        protected Thread mThread;

        public LobbyServerLink(LobbyServer lobbyServer)
        {
            this.mLobby = lobbyServer;
        }

        private void SendThread()
        {
            this.mInternal = new IPEndPoint(Tools.localAddress, this.mGameServer.tcpPort);
            this.mExternal = new IPEndPoint(Tools.localAddress, this.mGameServer.tcpPort);
            if (this.mLobby is UdpLobbyServer)
            {
                while (!this.mShutdown)
                {
                    long num = DateTime.UtcNow.Ticks / 0x2710L;
                    if ((this.mNextSend < num) && (this.mGameServer != null))
                    {
                        this.mNextSend = num + 0xbb8L;
                        this.mLobby.AddServer(this.mGameServer.name, this.mGameServer.playerCount, this.mInternal, this.mExternal);
                    }
                    Thread.Sleep(10);
                }
            }
            else
            {
                this.mLobby.AddServer(this.mGameServer.name, this.mGameServer.playerCount, this.mInternal, this.mExternal);
            }
            this.mThread = null;
        }

        public virtual void SendUpdate(GameServer gameServer)
        {
            if (!this.mShutdown)
            {
                this.mGameServer = gameServer;
                if (this.mExternal != null)
                {
                    long num = DateTime.UtcNow.Ticks / 0x2710L;
                    this.mNextSend = num + 0xbb8L;
                    this.mLobby.AddServer(this.mGameServer.name, this.mGameServer.playerCount, this.mInternal, this.mExternal);
                }
                else if (this.mThread == null)
                {
                    this.mThread = new Thread(new ThreadStart(this.SendThread));
                    this.mThread.Start();
                }
            }
        }

        public virtual void Start()
        {
            this.mShutdown = false;
        }

        public virtual void Stop()
        {
            if (!this.mShutdown)
            {
                this.mShutdown = true;
                if ((this.mExternal != null) && (this.mLobby != null))
                {
                    this.mLobby.RemoveServer(this.mInternal, this.mExternal);
                }
            }
        }

        public virtual bool isActive
        {
            get
            {
                return ((this.mLobby != null) && (this.mExternal != null));
            }
        }
    }
}

